<?php
session_start();

header( 'Content-Type: application/json; charset=utf-8' );

require_once ("../conf/conf.php");
require_once ("../locales/ro.php");
require ("../include/constants.php");
require ("../include/function.php");

$action = isset ($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : "");

if(isset($_SESSION['user_id'])) {
    if($action == 'save'){
        $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
        echo saveKeyword();
        db_disconnect($connection);
    } else if($action == 'remove') {
        $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
        echo doRemove();
        db_disconnect($connection);
    } else {
        getKeywords();
    }
    /* else {
        echo renderExpectationFailed();
    }*/
} else {
	echo renderUnauthorized();
}


// ====================================================

function doRemove(){
    $userId = $_SESSION['user_id'];
    $id = (int)$_POST['id'];
    $sql = "DELETE FROM keywords WHERE id = $id AND user_id = $userId";
    $result = do_query($sql);
    if($result){
        return renderSuccess();
    }
    return renderError("Eroare la stergere"); // TODO i18n
}

// ====================================================
function saveKeyword(){
    $id = (int)$_POST['id'];

    // TODO verify $keywords for SQL Injection
    $keywords = trim($_POST['keywords']);
    // TODO verify $style for SQL Injection
    $style = trim($_POST['style']);
    // TODO verify $cls for SQL Injection
    $cls = trim($_POST['cls']);

    $enabled = (int)$_POST['enabled'];

    $userId = $_SESSION['user_id'];

    if(trim($keywords) == ''){
        return renderError("Eroare la salvare."); // TODO i18n
    }

    if($id){ // update
        $sql = "UPDATE keywords set keywords = '$keywords', ".
                "style = '$style', cls = '$cls', enabled = '$enabled' ".
                "WHERE id = $id AND user_id = $userId";
        $r = do_query($sql);
        $i = mysql_affected_rows();
        if($i == 1){
            return renderSuccess();
        }
    } else { // insert
        $sql = "INSERT INTO keywords(keywords, style, cls, enabled, user_id) ".
                "VALUES('$keywords','$style','$cls', '$enabled', $userId)";
        $r = do_query($sql);
        if($r == 1){
            return renderId(mysql_insert_id());
        }
    }

    return renderError("Eroare la salvare."); // TODO i18n;
}

// ====================================================
?>